<script setup lang="ts">
import {
  createFlower,
  deleteFlower,
  getFlowerTypeOptions,
  getAllPresaleFlower,
  updateFlower,
  updateFlowerStatus
} from "@/api/flower";
import { Flower, FlowerTypeOptionItem } from "types/flower";
import { ref, onMounted, reactive, computed, h, Fragment } from "vue";
import numeral from "numeral";
import dayjs from "dayjs";
import { IconifyIconOnline } from "@/components/ReIcon";
import { UPLOAD_IMAGE_URL } from "@/api/images";
import { ElUpload } from "element-plus";
import { isArray } from "@pureadmin/utils";
import { ImageItem } from "types/image";
import { FlowerMaterial, FlowerOccasion, FlowerReceiver } from "@/constants";
import {
  FieldValues,
  OptionsRow,
  PlusColumn,
  PlusDialogForm
} from "plus-pro-components";
import { message } from "@/utils/message";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const flowerList = ref<Flower[]>([]);

const state = reactive({
  loading: false
});

const loadData = async () => {
  try {
    flowerList.value = (await getAllPresaleFlower()) ?? [];
  } catch (error) {
    console.log(error);
  }
};

const getCover = (flower: Flower) => {
  if (flower.images && flower.images.length > 0) {
    return SERVER_URL + flower.images[0];
  }

  return "/images/flower.png";
};

const flowerTypeOptions = ref<OptionsRow[]>([]);
const flowerTypeMap = ref<Record<number, FlowerTypeOptionItem>>([]);

const loadFlowerType = async () => {
  try {
    const response = await getFlowerTypeOptions();
    flowerTypeOptions.value = response.map(item => ({
      label: item.name,
      value: item.id
    }));
    flowerTypeMap.value = response.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {});
  } catch (error) {
    console.log(error);
  }
};

const formRules = {
  name: [
    {
      required: true,
      message: "请输入名称"
    }
  ],
  type: [
    {
      required: true,
      message: "请选择分类"
    }
  ],
  quantity: [
    {
      required: true,
      message: "请输入库存"
    }
  ],
  original_price: [
    {
      required: true,
      message: "请输入原价"
    }
  ],
  price: [
    {
      required: true,
      message: "请输入价格"
    }
  ],
  status: [
    {
      required: true,
      message: "请选择状态"
    }
  ],
  presale_date: [
    {
      required: true,
      message: "请输入预售时间"
    }
  ]
};

const submitLoading = ref<boolean>(false);
const formVisible = ref(false);
const formData = ref<FieldValues>({});
const formColumns: PlusColumn[] = [
  {
    label: "名称",
    prop: "name",
    valueType: "input"
  },
  {
    label: "描述",
    prop: "description",
    valueType: "textarea"
  },
  {
    label: "枝数",
    prop: "size",
    valueType: "input-number",
    colProps: {
      span: 12
    }
  },
  {
    label: "对象",
    prop: "receiver",
    valueType: "select",
    options: FlowerReceiver,
    colProps: {
      span: 12
    }
  },
  {
    label: "花材",
    prop: "material",
    valueType: "select",
    options: FlowerMaterial,
    colProps: {
      span: 12
    }
  },
  {
    label: "场合",
    prop: "occasion",
    valueType: "select",
    options: FlowerOccasion,
    colProps: {
      span: 12
    }
  },
  {
    label: "分类",
    prop: "type",
    valueType: "select",
    options: computed(() => flowerTypeOptions.value),
    colProps: {
      span: 12
    }
  },
  {
    label: "原价",
    prop: "original_price",
    valueType: "input-number",
    colProps: {
      span: 12
    }
  },
  {
    label: "售价",
    prop: "price",
    valueType: "input-number",
    colProps: {
      span: 12
    }
  },
  {
    label: "标签",
    prop: "tags",
    valueType: "plus-input-tag"
  },
  {
    label: "鲜花图片",
    prop: "images",
    valueType: "img",
    tooltip: "第一张图片将作为封面",
    renderField(value: string[], onChange) {
      const images = isArray(value) ? value : [];
      console.log(images);
      return h(Fragment, [
        h(
          ElUpload,
          {
            fileList: images.map(item => ({
              name: item,
              url: SERVER_URL + item
            })),
            action: UPLOAD_IMAGE_URL,
            listType: "picture-card",
            onSuccess: async (data: ImageItem) => {
              console.log(data);
              onChange([
                ...value,
                `/static/images/${data.folder}/${data.hash}.${data.format}`
              ]);
            },
            onRemove(uploadFile, uploadFiles) {
              console.log(uploadFile, uploadFiles);
              onChange(uploadFiles.map(item => item.name));
            }
          },
          [h(IconifyIconOnline, { icon: "ep:plus" })]
        )
      ]);
    }
  },
  // {
  //   label: "预售",
  //   prop: "presale",
  //   valueType: "switch",
  //   colProps: {
  //     span: 24
  //   }
  // },
  {
    label: "预售时间",
    prop: "presale_date",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      onChange: () => {
        formData.value.presale_delivery_date = null;
      }
    },
    colProps: {
      span: 12
    },
    hideInForm: computed(() => !formData.value.presale)
  },
  {
    label: "预售发货时间",
    prop: "presale_delivery_date",
    valueType: "date-picker",
    fieldProps: {
      type: "daterange",
      disabledDate: time => {
        if (formData.value.presale_date) {
          return dayjs(time) < dayjs(formData.value.presale_date[1]);
        }
        return false;
      }
    },
    colProps: {
      span: 12
    },
    hideInForm: computed(() => !formData.value.presale)
  }
];

const handleEdit = (e: Flower) => {
  const data: any = {
    id: e.id,
    name: e.name,
    description: e.description,
    images: e.images,
    original_price: e.original_price,
    price: e.price,
    receiver: e.receiver,
    material: e.material,
    size: e.size,
    type: e.type,
    occasion: e.occasion,
    tags: e.tags,
    presale: e.presale
  };

  if (e.presale) {
    if (e.presale_start_date && e.presale_end_date) {
      data.presale_date = [e.presale_start_date, e.presale_end_date];
    }

    if (e.presale_delivery_start_date && e.presale_delivery_end_date) {
      data.presale_delivery_date = [
        e.presale_delivery_start_date,
        e.presale_delivery_end_date
      ];
    }
  }

  formData.value = data;

  formVisible.value = true;
};

const handleConfirm = async e => {
  try {
    submitLoading.value = true;

    if (e.presale) {
      if (e.presale_date) {
        e.presale_start_date = dayjs(e.presale_date[0]).startOf("day");
        e.presale_end_date = dayjs(e.presale_date[1]).endOf("day");
      }

      if (e.presale_delivery_date) {
        e.presale_delivery_start_date = dayjs(
          e.presale_delivery_date[0]
        ).startOf("day");
        e.presale_delivery_end_date = dayjs(e.presale_delivery_date[1]).endOf(
          "day"
        );
      }
    }

    if (formData.value.id) {
      await updateFlower(e);
    } else {
      await createFlower(e);
    }
    message("保存成功", { type: "success" });
    formVisible.value = false;
    loadData();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  } finally {
    submitLoading.value = false;
  }
};

const handleNew = () => {
  formData.value = {
    images: [],
    presale: true
  };
  formVisible.value = true;
};

const handleUpdateFlowerStatus = async (data: Flower) => {
  try {
    if (data.status === 1) {
      await updateFlowerStatus({ id: data.id, status: 2 });
    } else {
      await updateFlowerStatus({ id: data.id, status: 1 });
    }
    message("更新成功", { type: "success" });
    loadData();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("更新失败", { type: "error" });
    }
    console.log(e);
  }
};

onMounted(() => {
  loadFlowerType();
  loadData();
});
</script>
<template>
  <div>
    <div v-if="!state.loading && flowerList.length === 0">
      <el-empty />
    </div>
    <div class="flex justify-end items-center pb-4">
      <el-space>
        <el-button type="primary" @click="handleNew">
          <template #icon>
            <IconifyIconOnline icon="ep:plus" />
          </template>
          新增
        </el-button>
      </el-space>
    </div>
    <el-row :gutter="16">
      <el-col
        v-for="item in flowerList"
        :key="item.id"
        :sm="24"
        :md="12"
        :lg="8"
      >
        <el-card shadow="hover" class="mb-4">
          <template #header>
            <div class="flex items-center justify-between">
              <div class="truncate">{{ item.name }}</div>
              <el-dropdown trigger="click">
                <el-button link type="primary">
                  <IconifyIconOnline icon="ep:more-filled" />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleEdit(item)">
                      <IconifyIconOnline icon="ep:edit-pen" />
                      &nbsp;&nbsp;编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="item.status === 1"
                      @click="handleUpdateFlowerStatus(item)"
                    >
                      <IconifyIconOnline icon="ep:delete" />
                      &nbsp;&nbsp;下架
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-else-if="item.status === 2"
                      @click="handleUpdateFlowerStatus(item)"
                    >
                      <IconifyIconOnline icon="ep:upload" />
                      &nbsp;&nbsp;上架
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <!-- <el-button link type="primary" @click="handleEdit(item)">
                <IconifyIconOnline icon="ep:edit-pen" />
              </el-button> -->
            </div>
          </template>
          <div class="flex">
            <el-image
              class="shrink-0 mr-2"
              style="width: 130px; height: 130px"
              :src="getCover(item)"
            />
            <el-descriptions :column="1" border size="small" class="w-full">
              <el-descriptions-item label="状态">
                <el-tag v-if="item.status === 1" type="success">预售</el-tag>
                <el-tag v-else-if="item.status === 2" type="info">下架</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="价格">
                {{ `￥${numeral(item.price).format("0.00")}` }}
              </el-descriptions-item>
              <el-descriptions-item label="销量">
                {{ item.sales_count }}
              </el-descriptions-item>
              <el-descriptions-item label="预售时间">
                {{
                  dayjs(item.presale_start_date).format("YYYY-MM-DD") +
                  " ~ " +
                  dayjs(item.presale_end_date).format("YYYY-MM-DD")
                }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <PlusDialogForm
      v-model:visible="formVisible"
      v-model="formData"
      :destroy-on-close="true"
      :title="formData.id ? '编辑鲜花' : '添加鲜花'"
      :form="{
        columns: formColumns,
        rules: formRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
      :confirmLoading="submitLoading"
      @confirm="handleConfirm"
    />
  </div>
</template>
<style scoped lang="scss">
.el-card {
  --el-card-padding: 12px;
}
</style>
